<template>
  <div class="news-list">
    <div class="header">
      <h2>新闻列表</h2>
      <!-- 只有管理员可以发布新闻 -->
      <el-button v-if="userStore.isAdmin" type="primary" @click="handleAdd">发布新闻</el-button>
    </div>

    <el-table :data="newsList" style="width: 100%" v-loading="loading">
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="content" label="内容" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ scope.row.content ? scope.row.content.toString() : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="发布时间">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" v-if="userStore.isAdmin">
        <template #default="scope">
          <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-model:page="currentPage"
      v-model:size="pageSize"
      :total="total"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { getList, remove } from '@/api/news'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import Pagination from '@/components/Pagination.vue'

const userStore = useUserStore()
const router = useRouter()

const loading = ref(false)
const newsList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

const loadData = async () => {
  loading.value = true
  try {
    const res = await getList({
      page: currentPage.value,
      size: pageSize.value
    })
    console.log('加载新闻数据响应:', res)
    if (res.code === 200 && res.data) {
      newsList.value = (res.data.records || []).map(item => ({
        ...item,
        content: item.content ? item.content.toString() : ''
      }))
      total.value = res.data.total || 0
      currentPage.value = res.data.current || 1
      pageSize.value = res.data.size || 10
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取新闻列表失败:', error)
    ElMessage.error('获取新闻列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  router.push('/admin/news/add')
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该新闻吗？', '提示', {
      type: 'warning'
    })
    const res = await remove(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleEdit = (row) => {
  router.push(`/admin/news/edit/${row.id}`)
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.news-list {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
      color: #000; /* 添加黑色 */
    }
  }
}

.el-button {
  margin-right: 10px;
}

.el-button:last-child {
  margin-right: 0;
}
</style> 